<!-- 技能列表 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot-scope="{ row }" slot="status">
        <el-tag :class="row.status == 1 ? 'successTag' : 'dangerTag'">{{ row.status == 1 ? '启用' : '禁用' }}</el-tag>
      </template>
      <template slot-scope="{ row }" slot="isValidPeriod">
        <el-tag :class="row.isValidPeriod ? 'successTag' : 'dangerTag'">{{ row.isValidPeriod ? '是' : '否' }}</el-tag>
      </template>
      <template slot="menuLeft">
        <el-button type="success" size="small" icon="el-icon-upload2" v-if="permission.skill_list_import" @click="showImportDialog = true">导 入</el-button>
        <el-button type="warning" size="small" plain icon="el-icon-download" v-if="permission.skill_list_export" @click="$refs.exportComp.visible = true">导 出</el-button>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="attachmentForm">
        <el-upload
          ref="skillAttachment"
          :disabled="isView"
          class="importConfigDialog"
          drag
          action="/api/blade-resource/oss/endpoint/put-file-attach"
          :headers="headersObj"
          style="width: 50%"
          accept=".png,.gif,.bmp,.jpg,.jpeg,.doc,.docx,.xlsx,.xls,.pdf"
          :before-upload="handleBeforeUpload"
          :on-remove="removeFile"
          :on-success="handleUploadSuccess"
          :on-preview="handlePreview"
          :file-list="fileList"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        </el-upload>
      </template>
    </avue-crud>

    <importDialogComp
      title="技能列表导入"
      url="/api/mes-admin/skill/import"
      export-name="技能列表导入模板.xlsx"
      :form-data="fromData"
      :is-form-data-json="true"
      :visible.sync="showImportDialog"
      :config-columns="['dataRepeat']"
      @submit="codeClose"
      :params="{}"
    ></importDialogComp>
    <export-comp ref="exportComp" page-api-url="mes-admin/skill/page" :option="option" :page="page" :query="query" file-name="技能列表"></export-comp>

    <!-- 预览功能 -->
    <el-dialog
      ref="dialog"
      title="查看PDF"
      append-to-body
      :visible.sync="showPDFPreviewDialog"
      :full-screen="fullScreen"
      :class="[fullScreen ? 'fullscreen' : 'no_fullScreen']"
      :close-on-click-modal="false"
      @close="fullScreen = false"
    >
      <iframe ref="pdf" :src="pdfUrl" width="100%" :height="iframeHeight"></iframe>
      <div slot="title" class="dialog-title">
        <span class="title">查看PDF</span>
        <span class="el-dialog__close fullscreen-icon" @click="fullScreen = !fullScreen">
          <i class="el-icon-full-screen"></i>
        </span>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="showPDFPreviewDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>

    <doc-preview :url="fileUrl" :visiable.sync="previewVisible" :file-type="fileType"></doc-preview>
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex';
import { getList, getDetail, add, update, remove } from '@/api/product/skill-list';
import userConfig from '@/mixins/userConfig'; // handleSetUserConfig
// 组件
import userTableConfig from '@/components/user-table-config';
import importDialogComp from '@/components/dialog/import';
import exportComp from '@/components/export-comp';
import { getToken } from '@/util/auth';
import { crudOptionHelper, inputOptionHelper, selectOptionHepler, switchOptionHelper, textareaOptionHelper, columnOptionHelper } from './skillsHelperFunction';
import DocPreview from '@/components/filePreview/docPreview';
import { downLoad } from '@/api/resource/attach';
import { Base64 } from 'js-base64';
import website from '@/config/website';

const PAGE_NAME = 'skill_list';

export default {
  name: PAGE_NAME,
  mixins: [userConfig()],
  components: {
    userTableConfig,
    importDialogComp,
    exportComp,
    DocPreview
  },
  computed: {
    ...mapGetters(['permission']),
    // avue-crud :permission
    permissionList() {
      // 权限控制-需要去菜单管理（system/menu）中配置
      return {
        addBtn: this.vaildData(this.permission[PAGE_NAME + '_add'], false),
        viewBtn: this.vaildData(this.permission[PAGE_NAME + '_view'], false),
        delBtn: this.vaildData(this.permission[PAGE_NAME + '_delete'], false),
        editBtn: this.vaildData(this.permission[PAGE_NAME + '_edit'], false)
      };
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    },
    iframeHeight() {
      const docHeight = document.documentElement.clientHeight;
      const iframeHeight = docHeight - 194 + 'px';
      return this.fullScreen ? iframeHeight : '600px';
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(',');
    }
  },
  data() {
    return {
      isView: false,
      fileList: [],
      pageCode: PAGE_NAME,
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      showPDFPreviewDialog: false,
      fullScreen: '',

      query: {},

      selectionList: [],
      // avue-crud :option
      option: crudOptionHelper({
        column: [
          selectOptionHepler({ label: '技能类型', prop: 'type', order: 1, dicUrl: '/api/blade-system/dict/dictionary?code=skill_type' }),
          inputOptionHelper({ label: '技能名称', prop: 'name', order: 2 }),
          inputOptionHelper({ label: '技能编码', prop: 'code', order: 3, hide: true, search: false }),
          selectOptionHepler({ label: '技能等级', prop: 'level', order: 4, required: false, dicUrl: '/api/blade-system/dict/dictionary?code=skill_level' }),
          switchOptionHelper({
            label: '管控技能有效期',
            prop: 'isValidPeriod',
            order: 6,
            value: true,
            dicData: [
              { label: '禁用', value: false },
              { label: '启用', value: true }
            ]
          }),
          switchOptionHelper({
            label: '状态',
            prop: 'status',
            order: 5,
            value: 1,
            dataType: 'number',
            dicData: [
              { label: '否', value: 0 },
              { label: '是', value: 1 }
            ]
          }),
          textareaOptionHelper({ label: '备注', prop: 'remark' }),
          columnOptionHelper({ label: '更新人', prop: 'updateUser' }),
          columnOptionHelper({ label: '更新时间', prop: 'updateTime' }),
          { label: '附件', prop: 'attachment', hide: true, formslot: true, span: 24 }
        ]
      }),
      // avue-crud :table-loading
      loading: true,
      // avue-crud :data
      data: [],
      // avue-crud :defaults.sync
      defaults: {},
      // avue-crud :page.sync
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      // avue-crud v-model
      form: {},

      // importDialogComp :form-data
      fromData: {},
      // importDialogComp :visible.sync
      showImportDialog: false,
      previewVisible: false,
      fileType: '',
      fileUrl: '',
      pdfUrl: ''
    };
  },

  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });

    // 获取部门树形数据
    // let tenantId = JSON.parse(localStorage.getItem('saber-tenantId') || '{}').content;
    // this.initData(tenantId);
  },
  methods: {
    // initData(tenantId) {
    //   getDeptTree(tenantId).then((res) => {
    //     const column = this.findObject(this.option.column, 'deptId');
    //     column.dicData = res.data.data;
    //   });
    // },
    // avue-crud :before-open
    beforeOpen(done, type) {
      this.fileList = [];
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data || this.form;
          let attachJson = res.data.data.attachJson || '[]';
          this.fileList = JSON.parse(attachJson);
        });
      }
      this.isView = type == 'view';
      done();
    },
    /**表格操作 START */
    rowUpdate(row, index, done, loading) {
      let attachJson = this.fileList || [];
      attachJson = JSON.stringify(attachJson);
      let params = { ...row, attachJson };
      update(params).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowSave(row, done, loading) {
      let attachJson = this.fileList || [];
      attachJson = JSON.stringify(attachJson);
      let params = { ...row, attachJson };
      add(params).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    searchChange(params, done) {
      // if (params.deptId) {
      //   params.deptName = params.deptId;
      //   delete params.deptId;
      // }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    /**表格操作 END*/

    // 导入关闭
    codeClose(value, data) {
      this.onLoad(this.page);
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    },

    // 文件上传
    handleBeforeUpload(file) {
      return this.validateFileType(file);
    },
    handleUploadSuccess(res) {
      this.fileList.push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        name: res.data.originalName
      });
    },
    removeFile(file) {
      this._forEach(this.fileList, (item, index) => {
        if (item.attachmentId === file.attachmentId) {
          this.fileList.splice(index, 1);
        }
      });
    },
    // async handleBeforeRemove(file, fileList) {
    //   let res = await this.$confirm(`确定移除 ${file.name}？`, {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   });
    //   if (res) {
    //     this.form.attachment = {};
    //     this.$message({
    //       type: 'success',
    //       message: '移除成功!'
    //     });
    //   }
    // },
    getFileType(url) {
      // 从URL中提取文件名
      const filename = url.split('/').pop();
      // 提取文件名的扩展名
      const fileExtension = filename.split('.').pop();
      return fileExtension;
    },
    validateFileType(file) {
      const acceptFileTypes = ['png', 'gif', 'bmp', 'jpeg', 'jpg', 'doc', 'docx', 'xlsx', 'xls', 'pdf'];
      const isSuitFileType = acceptFileTypes.includes(this.getFileType(file.name));
      if (isSuitFileType) {
        // file保存选择的文件
        // this.fileList.push({})
      } else {
        this.$message({
          message: '上传文件只能是图片或者word、excel、pdf格式',
          type: 'warning',
          duration: 2000
        });
      }
      const isLt10MB = file.size / 1024 / 1024 < 10;
      if (!isLt10MB) {
        this.$message.error('上传文件大小不能超过 10MB');
      }
      return isSuitFileType && isLt10MB;
    },
    handleFullScreen() {
      this.fullScreen = !this.fullScreen;
    },
    handlePreview(file) {
      const { name, link: url } = file;
      const fileType = this.getFileType(url);
      if (['doc', 'docx', 'xlsx', 'xls'].includes(fileType)) {
        this.previewVisible = true;
        this.fileUrl = url;
        this.fileType = fileType;
        return;
      }
      if (url.indexOf('pdf') != -1) {
        downLoad({ link: url }).then(
          (res) => {
            let fileURL = null;
            var blob = new Blob([res.data], { type: 'application/pdf' });
            if (window.createObjectURL != undefined) {
              // basic
              fileURL = window.createObjectURL(blob);
            } else if (window.webkitURL != undefined) {
              // webkit or chrome
              try {
                fileURL = window.webkitURL.createObjectURL(blob);
              } catch (error) {
                console.log(error);
              }
            } else if (window.URL != undefined) {
              // mozilla(firefox)
              try {
                fileURL = window.URL.createObjectURL(blob);
              } catch (error) {
                console.log(error);
              }
            }
            this.pdfUrl = '/pdf/web/viewer.html?file=' + encodeURIComponent(fileURL);
            this.showPDFPreviewDialog = true;
          },
          (error) => {}
        );
      } else {
        if (this.isImageFile(url || file.url)) {
          this.$ImagePreview([{ url: url ? url : file.url }], 0, {
            closeOnClickModal: false
          });
        } else {
          window.open(url || file.url);
        }
      }
    },
    isImageFile(filename) {
      let ext = filename.split('.').pop().toLowerCase();
      return ['jpg', 'jpeg', 'png', 'gif', 'bmp'].includes(ext);
    }
  }
};
</script>

<style scoped lang="scss">
.importConfigDialog .el-upload {
  width: 100%;
}

.importConfigDialog .el-upload-dragger {
  width: 100%;
}

.custom-upload {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.model-download {
  cursor: pointer;

  .icon-color {
    color: #409eff;
    margin-right: 4px;
    font-size: 16px;
  }

  :hover {
    color: #409eff;
  }
}

.dialog-title {
  position: relative;
  .title {
    display: inline-block;
  }
  .fullscreen-icon {
    position: absolute;
    right: 20px;
    cursor: pointer;
    display: inline-block;
    font-size: 14px;
    color: #909399;
    &:hover {
      color: #0a84ff;
    }
  }
}
.fullscreen {
  ::v-deep .el-dialog {
    width: 100%;
    margin: 0 !important;
    margin-top: 0vh !important;
  }
}
.no_fullScreen {
  ::v-deep.el-dialog {
    width: 50%;
    margin-top: 5vh !important;
  }
}
</style>
